/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package request.general;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import system.general.Exc;
import system.general.Logged;
import system.general.Persistencia;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "request_generalFind")
@FacesConverter(value = "request_generalFind")
@ViewScoped
public class Find implements Converter {

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Beans selectedBean = new Beans();
    private String sql = "";
    private String command = "SELECT s.id, idl_accion, id_facultad,id_recepcionista,carrera, "
            + "observacion, u.id AS id_universidad, u.nombre AS nombreuniversidad, f.nombre AS nombrefacultad, "
            + "p.nombre AS nombrepersona, recibido, registrado FROM public.v_solicitud_general s "
            + "INNER JOIN public.v_universidad_facultad f "
            + "ON (s.id_facultad = f.id) "
            + "INNER JOIN public.v_universidad_general u "
            + "ON (f.id_universidad=u.id) "
            + "INNER JOIN public.v_persona_general p "
            + "ON (s.id_recepcionista = p.id) WHERE ";
    private String order = "ORDER BY carrera ";

    public Find() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
    }

    public Beans getSelected() {
        return selectedBean;
    }

    public void setSelected(Beans bean) {
        if (bean != null) {
            logged.setDetailId(selectedBean.getId());
        }
    }

    public List<Beans> getListByLoggedMap() throws Exc, SQLException, Exception {
        if (logged.getMap().isEmpty()) {
            return null;
        }
        return byMap(logged.getMap());
    }

    public List<Beans> getListByLoggedId() throws Exc, SQLException, Exception {
        if (logged.getMasterId() != 0) {
            Map<String, String> map = new LinkedHashMap<>();
            map.put("s.id_facultad = " + logged.getMasterId(), " ");
            return byMap(map);
        }
        return null;
    }

    public boolean byExist(Map map) throws Exc, SQLException, Exception {
        List<Beans> listBean = byMap(map);
        if (listBean.isEmpty()) {
            listBean.clear();
            return false;
        }
        listBean.clear();
        return true;
    }

    public List<Beans> byMap(Map map) throws Exc, SQLException, Exception {
        Iterator it = map.entrySet().iterator();
        StringBuilder criteria = new StringBuilder("");
        while (it.hasNext()) {
            Map.Entry e = (Map.Entry) it.next();
            criteria.append(e.getKey().toString());
            criteria.append(e.getValue().toString());
        }
        sql = command + criteria + order;
        return executeSql(sql);
    }

    private List<Beans> executeSql(String sql) throws Exc, SQLException, Exception {
        List<Beans> list = new ArrayList<>();
        list.clear();
        ResultSet rsts = persistencia.executeRsts(sql);
        while (rsts.next()) {
            Beans beans = new Beans(
                    rsts.getInt("id"),
                    rsts.getInt("idl_accion"),
                    rsts.getDate("recibido"),
                    rsts.getDate("registrado"),
                    rsts.getInt("id_recepcionista"),
                    rsts.getInt("id_facultad"),
                    rsts.getString("carrera"),
                    rsts.getString("observacion"),
                    rsts.getInt("id_universidad"),
                    rsts.getString("nombreuniversidad"),
                    rsts.getString("nombrefacultad"),
                    rsts.getString("nombrepersona"));
            list.add(beans);
        }
        //Desconecta de la base de datos debido a que es un resultset y podria quedar la conexion activa
        persistencia.dbDisconnect();
        return list;
    }

    private String strChar(String data) {
        data = data.toLowerCase().trim();
        data = data.replaceAll("Ã¡", "a");
        data = data.replaceAll("Ã©", "e");
        data = data.replaceAll("Ã­", "i");
        data = data.replaceAll("Ã³", "o");
        data = data.replaceAll("Ãº", "u");
        data = data.replaceAll("a", "[a,Ã¡]");
        data = data.replaceAll("e", "[e,Ã©]");
        data = data.replaceAll("i", "[i,Ã­]");
        data = data.replaceAll("o", "[o,Ã³]");
        data = data.replaceAll("u", "[u,Ãº]");
        return data;
    }

    /*
     * @Override public Object getAsObject(FacesContext facesContext,
     * UIComponent component, String submittedValue) { if
     * (submittedValue.trim().equals("0")) { return null; } int number =
     * Integer.parseInt(submittedValue); logged.setRecordId(number); return
     * null; }
     */
    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {

        if (submittedValue.trim().equals("0")) {
            return null;
        }
        int id = Integer.parseInt(submittedValue.substring(0, submittedValue.indexOf("-")));
        String carrera = submittedValue.substring(submittedValue.indexOf("-") + 1, submittedValue.length());
        logged.setMasterId(id);
        logged.setMasterName(carrera);
        return null;
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
        if (value == null || value.equals("")) {
            return "";
        }
        //      logged.setTempId(0);
        return String.valueOf(((Beans) value).getId()) + "-" + ((Beans) value).getCarrera() + " " + ((Beans) value).getObservacion();
    }
}
